package com.hotel.service.impl;

import com.hotel.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;

@Service
public class MailServiceImpl implements MailService{
  public static final String SUBJECT="火烧燎酒店登录验证码";
  //注入一个java对象
  @Autowired
  private JavaMailSender sender;
    //做环境配置
    @Autowired
    private Environment environment;

  @Override
  public void sendEmail(String to, String subject, String text) {
    SimpleMailMessage message=new SimpleMailMessage();
    message.setFrom(environment.getProperty("spring.mail.username"));
    message.setTo(to);
    message.setSubject(subject);
    message.setText(text);
    sender.send(message);
  }

  @Override
  public int sendLoginCodeEmail(String to) throws MessagingException {
    MimeMessage message=sender.createMimeMessage();
    MimeMessageHelper helper=new MimeMessageHelper(message,true);
    helper.setFrom(environment.getProperty("spring.mail.username"));
    helper.setTo(to);
    helper.setSubject(SUBJECT);
    int code=(int)((Math.random()*9+1)*1000);
String htmlContent="您的账号于"+ LocalDateTime.now()+"在"+environment.getProperty("spring.application.name")+"登录"+
        "验证码为：<h3>"+code+"</h3>";
helper.setText(htmlContent,true);
sender.send(message);
return code;
  }
}
